package com.stx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stx.common.PageValue;
import com.stx.common.Rank;
import com.stx.common.Result;
import com.stx.pojo.Judge;
import com.stx.pojo.Match;
import com.stx.pojo.Player;
import com.stx.pojo.Ruanyue;
import com.stx.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

@CrossOrigin
@RestController
@Tag(name = "选手相关接口")
@RequestMapping("/player")
public class PlayerController {
    @Autowired
    private PlayerService playerService;
    @Autowired
    private MatchService matchService;
    @Value("${excel.path}")
    private String excelPath;

    @Autowired
    private IPlayerService jplayerService;
    @Autowired
    private IRuanyueService jruanyueService;
    @Autowired
    private IMatchService jmatchService;

    // 获取日志记录器
    private static final Logger logger = LogManager.getLogger(PlayerController.class);

    @Operation(
            summary = "列表",
            description = "选手列表",
            tags = {"选手相关接口"}
    )
    @GetMapping("/list")
    public Result getplayer() {
        List<Player> list = jplayerService.list();
        logger.info("获取选手列表成功");
        return Result.success(list);
    }

    @Operation(
            summary = "添加/修改接口",
            description = "选手添加和修改列表",
            tags = {"选手相关接口"}
    )
    @PostMapping("/save")
    public Result save(@Valid @RequestBody Player player) {
        player.setPlaDate(LocalDateTime.now());
        jplayerService.saveOrUpdate(player);
        return Result.success();
    }

    @Operation(
            summary = "删除接口",
            description = "选手删除接口，根据id删除",
            tags = {"选手相关接口"}
    )
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        jplayerService.removeById(id);
        return Result.success();
    }

    @Operation(
            summary = "排序接口",
            description = "选手按照分数排序",
            tags = {"选手相关接口"}
    )
    @GetMapping("/orderby")
    public Result getRank() {
        try {
            LambdaQueryWrapper<Ruanyue> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Ruanyue::getRuaState, 1);
            Ruanyue one = jruanyueService.getOne(wrapper);
            if(one == null){
                logger.warn("当前没有进行中的比赛");
                return Result.error("当前没有进行中的比赛");
            }
            logger.info("当前比赛为：" + one);
            LambdaQueryWrapper<Match> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(Match::getRuaId, one.getId());
            List<Match> listMatch = jmatchService.getBaseMapper().selectList(wrapper1);
            List<Player> listPlayer = playerService.getplayer();
            for (Match match : listMatch) {
                for (Player player : listPlayer) {
                    if (match.getMatName().equals(player.getPlaName())) {
                        //找到之后在添加比赛表的分数在玩家表中
                        player.setAvgScore(match.getMatScore());
                        player.setRuaNumber(one.getRuaNumber());
                    }
                }
            }
            //排序后
            List<Player> rank = Rank.getRank(listPlayer);
        /*for (Player player : rank) {
            if (player.getAvgScore()==0.0){
                rank.remove(player);
            }
        }*/
            //注意遍历集合的同时不能够修改集合，所以上面代码会报错
            Iterator<Player> iterator = rank.iterator();
            while (iterator.hasNext()) {
                Player player = iterator.next();//返回迭代器的下一个元素，并将指针移向下一个元素
                if (player.getAvgScore() == null) {
                    iterator.remove();
                }
            }
            logger.info("选手排序后的排名为："+rank);
            return Result.success(rank);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    @Operation(
            summary = "分页查询选手表",
            description = "分页查询选手表(姓名/部门)",
            tags = {"选手相关接口"}
    )
    @PostMapping("/page")
    public Result findPage(@Validated @RequestBody PageValue pageValue) {
        if (pageValue.getCurrentPage() != null && pageValue.getPageSize() != null) {
            Page<Player> page = playerService.find(pageValue.getPlaName(), pageValue.getDepartment(), pageValue.getCurrentPage(), pageValue.getPageSize());
            return Result.success(page);
        } else {
            List<Player> list = jplayerService.list();
            return Result.success(list);
        }
    }

    @Operation(
            summary = "上传excel文件接口",
            description = "上传excel文件接口",
            tags = {"选手相关接口"}
    )
    @PostMapping("/excel")
    public Result uploadExcel(@RequestParam("file") MultipartFile file,@RequestParam("overwrite") boolean overwrite) {
        try {
            if (file.isEmpty()) {
                return Result.error("File is empty");
            }
            //建立文件夹
            File fileExcel = new File(excelPath);
            if (!fileExcel.exists()){
                fileExcel.mkdirs();
            }
            // 文件处理成功
            String fileName = file.getOriginalFilename();
            String substring = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
            //File.separator用来代替\\提高文件的跨平台可用
            String fileAddress = fileExcel + File.separator + substring;
            file.transferTo(new File(fileAddress));
            logger.info("文件位置：" + fileAddress);
            List<Player> ListError = new ArrayList<>();
            EasyExcel.read(fileAddress, Player.class,new PageReadListener<Player>(playerList -> {
                for (Player player : playerList) {
                    System.out.println(player);
                }
                if (overwrite){
                    System.out.println("覆盖");
                    for (Player player : playerList) {
                        List<Player> byName = jplayerService.findByName(player);
                        if (byName.size() != 0 ){
                            player.setId(byName.get(0).getId());
                            jplayerService.removeBatchByIds(byName);
                            player.setPlaState(1);
                            player.setPlaDate(LocalDateTime.now());
                            jplayerService.save(player);
                        }else {
                            player.setPlaDate(LocalDateTime.now());
                            player.setPlaState(1);
                            jplayerService.save(player);
                        }
                    }
                }else {
                    System.out.println("不覆盖");
                    for (Player player : playerList) {
                        if ("男".equals(player.getPlaGender()) || "女".equals(player.getPlaGender())){
                            player.setPlaDate(LocalDateTime.now());
                            player.setPlaState(1);
                            jplayerService.save(player);
                        }else {
                            ListError.add(player);
                        }
                    }
                }
                //boolean b = jplayerService.saveBatch(playerList);
            })).sheet().doRead();
            if (ListError.size() != 0){
                return Result.error("请检查"+ ListError.toString());
            }
            return Result.success("File uploaded successfully" + HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("File upload failed" + HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Operation(
            summary = "根据id查选手信息",
            description = "根据id查选手信息",
            tags = {"选手相关接口"}
    )
    @PostMapping("/info")
    public Result getfindInfo(@RequestBody Player player){
        LambdaQueryWrapper<Player> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(Player::getId,player.getId());
        List<Player> list = jplayerService.list(wrapper);
        if (list.size()==0){
            return Result.error("该选手不存在");
        }
        return Result.success(list);
    }

}
